/*
 * @(#)MessageListener.java 0.0.1-SNAPSHOT
 *
 * Copyright Group B
 */
package grupb.upf.ms.listeners;

import grupb.upf.Controller.Controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 * <p>This component implements a PacketListener Interface. It receives
 * Content messages and shows them to the user through the GUI.</p>
 *
 * @version    0.0.1-SNAPSHOT
 * @author     Group B
 */
public final class MessageListener implements
        org.jivesoftware.smack.PacketListener {

    /**
     * The logger. A new logger <code>grupb.upf.ms.MessageListener</code>
     * is created to add the logs of this class.
     */
    private static final Log LOG =
            LogFactory.getLog(MessageListener.class);
    /**
     * The controller to send the changes.
     */
    private Controller controller;

    /**
     * Constructor of the Listener.
     * @param c the controller of the GUI to send the updates
     */
    public MessageListener(final Controller c) {
        this.controller = c;
    }

    /**
     * Processs the received packtets with content.
     * @param packet The packet
     */
    @Override
    public void processPacket(final Packet packet) {
        // Put the incoming message on the chat history or chat board.
        final Message msg = (Message) packet;
        final String from = msg.getFrom();
        if (LOG.isInfoEnabled()) {
            final StringBuffer sb =
                    new StringBuffer(msg.getSubject())
                    .append(" received from ").append(from);
            LOG.info(sb);
            }
        if (msg.getSubject().equalsIgnoreCase("InstantMessage")) {
            controller.instantMessageReceived(msg.getBody(), from);
        } else if (msg.getSubject().equalsIgnoreCase("Chat")) {
            controller.chatMessageReceived(msg.getBody(), from);
        }
    }
}
